package com.daxilong.starchen.player.fragment;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;

import android.provider.MediaStore;
import android.view.View;

import com.daxilong.starchen.player.activity.AudioPlayerActivity;
import com.daxilong.starchen.player.adapter.LocalAudioAdapter;
import com.daxilong.starchen.player.databinding.FragmentLocalAudioBinding;
import com.daxilong.starchen.player.model.MediaItem;

import java.util.ArrayList;

public class LocalAudioFragment extends BaseFragment {

    private FragmentLocalAudioBinding binding;
    private LocalAudioAdapter adapter;

    @Override
    public View getLayout() {
        binding = FragmentLocalAudioBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    public void initView(){
        adapter = new LocalAudioAdapter();
        binding.recyclerView.setAdapter(adapter);

        adapter.setItemClientListener(new LocalAudioAdapter.MyListOnClickItemListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getContext(), AudioPlayerActivity.class);
                intent.putExtra("position",position);
                getContext().startActivity(intent);

            }
        });
    }

    public void initData(){
        ArrayList<MediaItem> mediaItemsList = new ArrayList<>();

        ContentResolver contentResolver = getContext().getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] objects = {MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Audio.Media.DURATION,
                MediaStore.Audio.Media.SIZE,
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.ARTIST,};
        Cursor cursor = contentResolver.query(uri,objects,null,null,null);
        if(cursor != null){
            while ( cursor.moveToNext()){
                MediaItem mediaItem = new MediaItem();
                String name = cursor.getString(0);
                mediaItem.setName(name);
                long duration = cursor.getLong(1);
                mediaItem.setDuration(duration);
                long size = cursor.getLong(2);
                mediaItem.setSize(size);
                String data = cursor.getString(3);
                mediaItem.setData(data);
                String artist = cursor.getString(4);
                mediaItem.setArtist(artist);

                mediaItemsList.add(mediaItem);
            }
        }

        adapter.setDataList(mediaItemsList);

    }

}